 
using System.Diagnostics;

/// <summary>

/// FileThread: a class for sub-thread
/// </summary>

public class FileThread
{

    private int nStartPos;
    private int nTotalBytes;
    private string strFileName;
    public static UploadFileData UploadHandle;

    public delegate void UploadFileData(string FileName, int StartPos, byte[] bData);

    /// <summary>

    /// Constructor

    /// </summary>

    /// <param name="StartPos"></param>

    /// <param name="TotalBytes"></param>

    /// <param name="FileName"></param>

    public FileThread(int StartPos, int TotalBytes, string FileName)
    {

        //Init thread variant
        nStartPos = StartPos;
        nTotalBytes = TotalBytes;
        strFileName = FileName;
        //Only for debug

        Debug.WriteLine(string.Format("File name:{0} position: {1} total byte:{2}", strFileName, nStartPos, nTotalBytes));

    }



    /// <summary>

    /// Sub-thread entry function 

    /// </summary>

    /// <param name="stateinfo"></param>

    public void UploadFile(object stateinfo)
    {

        int nRealRead, nBufferSize;

        const int BUFFER_SIZE = 10240;



        using (FileStream fs = new FileStream(strFileName,

                   FileMode.Open, FileAccess.Read,

                   FileShare.Read))
        {

            string sName = strFileName.Substring(strFileName.LastIndexOf("//") + 1);

            byte[] bBuffer = new byte[BUFFER_SIZE];//Init 10k buffer

            fs.Position = nStartPos;

            nRealRead = 0;

            do
            {

                nBufferSize = BUFFER_SIZE;

                if (nRealRead + BUFFER_SIZE > nTotalBytes)

                    nBufferSize = nTotalBytes - nRealRead;



                nBufferSize = fs.Read(bBuffer, 0, nBufferSize);

                if (nBufferSize == BUFFER_SIZE)

                    UploadHandle(sName,

                        nRealRead + nStartPos,

                        bBuffer);

                else if (nBufferSize > 0)
                {

                    //Copy data 

                    byte[] bytData = new byte[nBufferSize];

                    Array.Copy(bBuffer, 0, bytData, 0, nBufferSize);



                    UploadHandle(sName,

                        nRealRead + nStartPos,

                        bytData);

                }



                nRealRead += nBufferSize;

            }

            while (nRealRead < nTotalBytes);

        }

        //Release signal

        ManualResetEvent mr = stateinfo as ManualResetEvent;

        if (mr != null)

            mr.Set();

    }

}

